<template>
  <div class="location-log-table">
    <!-- 查询表单 -->
    <div class="search-form" v-if="showSearch">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="定位类型" prop="locationType">
          <el-select v-model="queryParams.locationType" placeholder="请选择" clearable style="width: 120px">
            <el-option label="GPS" value="1"></el-option>
            <el-option label="基站" value="2"></el-option>
            <el-option label="WIFI" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar" v-if="showToolbar">
      <div class="toolbar-left">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['locator:log:export']"
        >导出</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-map-location"
          size="mini"
          @click="handleShowTrack"
          :disabled="!selection.length"
        >显示轨迹</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-video-play"
          size="mini"
          @click="handlePlayback"
          :disabled="!selection.length"
        >轨迹回放</el-button>
      </div>
      <div class="toolbar-right">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getList"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch = !showSearch"></el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="logList"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      :height="tableHeight"
      stripe
      border
    >
      <el-table-column type="selection" width="50" align="center" v-if="selectable" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      
      <el-table-column label="定位时间" align="center" prop="locationTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.locationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="经度" align="center" prop="longitude" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.longitude ? scope.row.longitude.toFixed(6) : '-' }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="纬度" align="center" prop="latitude" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.latitude ? scope.row.latitude.toFixed(6) : '-' }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="地址" align="center" prop="address" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.address || '解析中...' }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="定位类型" align="center" prop="locationType" width="100">
        <template slot-scope="scope">
          <el-tag :type="getLocationTypeColor(scope.row.locationType)" size="mini">
            {{ getLocationTypeText(scope.row.locationType) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="定位精度" align="center" prop="accuracy" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.accuracy ? scope.row.accuracy + 'm' : '-' }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="速度" align="center" prop="speed" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.speed ? scope.row.speed + 'km/h' : '-' }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="方向" align="center" prop="direction" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.direction ? scope.row.direction + '°' : '-' }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="电池电量" align="center" prop="batteryLevel" width="100">
        <template slot-scope="scope">
          <div class="battery-cell" v-if="scope.row.batteryLevel !== null">
            <el-progress 
              :percentage="scope.row.batteryLevel"
              :color="getBatteryColor(scope.row.batteryLevel)"
              :stroke-width="6"
              :show-text="false"
              style="width: 50px;"
            ></el-progress>
            <span class="battery-text">{{ scope.row.batteryLevel }}%</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      
      <el-table-column label="信号强度" align="center" prop="signalStrength" width="100">
        <template slot-scope="scope">
          <div class="signal-cell" v-if="scope.row.signalStrength">
            <div class="signal-bars">
              <div 
                v-for="i in 4" 
                :key="i"
                class="signal-bar"
                :class="{ active: i <= getSignalBars(scope.row.signalStrength) }"
              ></div>
            </div>
            <span class="signal-text">{{ scope.row.signalStrength }}dBm</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" v-if="showActions">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-map-location"
            @click="handleShowOnMap(scope.row)"
          >地图</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详情对话框 -->
    <el-dialog title="位置详情" :visible.sync="detailVisible" width="600px" append-to-body>
      <div class="detail-content" v-if="currentLog">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">定位时间:</span>
              <span class="value">{{ parseTime(currentLog.locationTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">经度:</span>
              <span class="value">{{ currentLog.longitude }}</span>
            </div>
            <div class="detail-item">
              <span class="label">纬度:</span>
              <span class="value">{{ currentLog.latitude }}</span>
            </div>
            <div class="detail-item">
              <span class="label">定位类型:</span>
              <span class="value">{{ getLocationTypeText(currentLog.locationType) }}</span>
            </div>
            <div class="detail-item full-width">
              <span class="label">地址:</span>
              <span class="value">{{ currentLog.address || '解析中...' }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>定位信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">定位精度:</span>
              <span class="value">{{ currentLog.accuracy ? currentLog.accuracy + 'm' : '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">速度:</span>
              <span class="value">{{ currentLog.speed ? currentLog.speed + 'km/h' : '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">方向:</span>
              <span class="value">{{ currentLog.direction ? currentLog.direction + '°' : '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">海拔:</span>
              <span class="value">{{ currentLog.altitude ? currentLog.altitude + 'm' : '-' }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>设备状态</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">电池电量:</span>
              <span class="value">{{ currentLog.batteryLevel ? currentLog.batteryLevel + '%' : '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">信号强度:</span>
              <span class="value">{{ currentLog.signalStrength ? currentLog.signalStrength + 'dBm' : '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">卫星数量:</span>
              <span class="value">{{ currentLog.satelliteCount || '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">网络类型:</span>
              <span class="value">{{ currentLog.networkType || '-' }}</span>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
        <el-button type="primary" @click="handleShowOnMap(currentLog)">在地图上显示</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '@/utils/ruoyi';

export default {
  name: 'LocationLogTable',
  props: {
    // 设备IMEI
    deviceImei: {
      type: String,
      required: true
    },
    // 是否显示搜索
    showSearch: {
      type: Boolean,
      default: true
    },
    // 是否显示工具栏
    showToolbar: {
      type: Boolean,
      default: true
    },
    // 是否显示操作列
    showActions: {
      type: Boolean,
      default: true
    },
    // 是否可选择
    selectable: {
      type: Boolean,
      default: true
    },
    // 表格高度
    tableHeight: {
      type: [String, Number],
      default: null
    },
    // 外部数据
    externalData: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      selection: [],
      // 总条数
      total: 0,
      // 位置日志表格数据
      logList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceImei: this.deviceImei,
        dateRange: [],
        locationType: null
      },
      // 日期选择器配置
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      // 详情对话框
      detailVisible: false,
      // 当前日志
      currentLog: null
    };
  },
  watch: {
    deviceImei: {
      handler(newVal) {
        this.queryParams.deviceImei = newVal;
        if (newVal) {
          this.getList();
        }
      },
      immediate: true
    },
    externalData: {
      handler(newData) {
        if (newData) {
          this.logList = newData;
          this.total = newData.length;
          this.loading = false;
        }
      },
      immediate: true
    }
  },
  created() {
    if (!this.externalData) {
      this.getList();
    }
  },
  methods: {
    /** 查询位置日志列表 */
    getList() {
      if (this.externalData) {
        return;
      }
      
      this.loading = true;
      
      // 模拟API调用
      setTimeout(() => {
        // 模拟数据
        const mockData = this.generateMockData();
        this.logList = mockData.rows;
        this.total = mockData.total;
        this.loading = false;
      }, 500);
    },

    /** 生成模拟数据 */
    generateMockData() {
      const data = [];
      const now = new Date();
      
      for (let i = 0; i < 50; i++) {
        const time = new Date(now.getTime() - i * 10 * 60 * 1000); // 每10分钟一条记录
        data.push({
          id: i + 1,
          deviceImei: this.deviceImei,
          locationTime: time,
          longitude: 116.397428 + (Math.random() - 0.5) * 0.1,
          latitude: 39.90923 + (Math.random() - 0.5) * 0.1,
          address: `北京市朝阳区某某街道${Math.floor(Math.random() * 100)}号`,
          locationType: Math.floor(Math.random() * 3) + 1,
          accuracy: Math.floor(Math.random() * 50) + 5,
          speed: Math.floor(Math.random() * 80),
          direction: Math.floor(Math.random() * 360),
          altitude: Math.floor(Math.random() * 100) + 50,
          batteryLevel: Math.floor(Math.random() * 100),
          signalStrength: -(Math.floor(Math.random() * 50) + 50),
          satelliteCount: Math.floor(Math.random() * 12) + 4,
          networkType: ['4G', '3G', 'WIFI'][Math.floor(Math.random() * 3)]
        });
      }
      
      return {
        rows: data.slice((this.queryParams.pageNum - 1) * this.queryParams.pageSize, this.queryParams.pageNum * this.queryParams.pageSize),
        total: data.length
      };
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.dateRange = [];
      this.queryParams.locationType = null;
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.selection = selection;
      this.$emit('selection-change', selection);
    },

    /** 行点击事件 */
    handleRowClick(row) {
      this.$emit('row-click', row);
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有位置日志数据项?').then(() => {
        this.$modal.loading('正在导出数据，请稍候...');
        // 模拟导出
        setTimeout(() => {
          this.$modal.closeLoading();
          this.$modal.msgSuccess('导出成功');
        }, 2000);
      });
    },

    /** 显示轨迹 */
    handleShowTrack() {
      if (this.selection.length === 0) {
        this.$modal.msgError('请选择要显示轨迹的记录');
        return;
      }
      this.$emit('show-track', this.selection);
    },

    /** 轨迹回放 */
    handlePlayback() {
      if (this.selection.length === 0) {
        this.$modal.msgError('请选择要回放的记录');
        return;
      }
      this.$emit('playback', this.selection);
    },

    /** 查看详情 */
    handleView(row) {
      this.currentLog = row;
      this.detailVisible = true;
    },

    /** 在地图上显示 */
    handleShowOnMap(row) {
      this.$emit('show-on-map', row);
    },

    /** 获取定位类型文本 */
    getLocationTypeText(type) {
      const typeMap = {
        '1': 'GPS',
        '2': '基站',
        '3': 'WIFI'
      };
      return typeMap[type] || '未知';
    },

    /** 获取定位类型颜色 */
    getLocationTypeColor(type) {
      const colorMap = {
        '1': 'success', // GPS
        '2': 'warning', // 基站
        '3': 'info'     // WIFI
      };
      return colorMap[type] || '';
    },

    /** 获取电池颜色 */
    getBatteryColor(level) {
      if (level >= 60) return '#67c23a';
      if (level >= 30) return '#e6a23c';
      return '#f56c6c';
    },

    /** 获取信号格数 */
    getSignalBars(strength) {
      if (!strength) return 0;
      const absStrength = Math.abs(strength);
      if (absStrength <= 70) return 4;
      if (absStrength <= 85) return 3;
      if (absStrength <= 100) return 2;
      return 1;
    },

    /** 解析时间 */
    parseTime
  }
};
</script>

<style scoped>
.location-log-table {
  background: white;
}

.search-form {
  padding: 18px 20px 0;
  margin-bottom: 10px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px 18px;
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  gap: 5px;
}

.battery-cell {
  display: flex;
  align-items: center;
  gap: 5px;
}

.battery-text {
  font-size: 12px;
  color: #606266;
  min-width: 30px;
}

.signal-cell {
  display: flex;
  align-items: center;
  gap: 5px;
}

.signal-bars {
  display: flex;
  align-items: end;
  gap: 1px;
  height: 12px;
}

.signal-bar {
  width: 2px;
  background-color: #dcdfe6;
  border-radius: 1px;
}

.signal-bar:nth-child(1) { height: 3px; }
.signal-bar:nth-child(2) { height: 6px; }
.signal-bar:nth-child(3) { height: 9px; }
.signal-bar:nth-child(4) { height: 12px; }

.signal-bar.active {
  background-color: #67c23a;
}

.signal-text {
  font-size: 12px;
  color: #606266;
}

.detail-content {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin: 0 0 15px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
  font-size: 14px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-item .label {
  font-weight: bold;
  color: #606266;
  width: 80px;
  flex-shrink: 0;
}

.detail-item .value {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    padding: 15px 10px 0;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 10px;
    padding: 0 10px 15px;
  }
  
  .toolbar-left,
  .toolbar-right {
    width: 100%;
    justify-content: center;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
}
</style>